<?php
namespace app\store\controller;

use think\Db;
use app\common\controller\Api;

/****
 * Class    Store
 * @name    店铺API文件
 * @author  晓月老板<1434926265@qq.com>
 * @date    2020/05/20 11:34 AM
 * @package app\api\controller
 */
class Goods extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    // 默认方法
    public function _initialize()
    {
        parent::_initialize();

        // 商品接口
        $this->model = new \app\admin\model\shopro\Goods;

        // 获取店铺ID
        $this->store_id = $this->request->request("store_id",0,"intval");
    }


    /***
     * @name    商户商品列表<按照后台权重排序>
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/05/22 14:51 PM
     * @return  string<json>
     */
    public function goods_list()
    {

        // 页数
        $offset = $this->request->get("offset", 0);

        // 获取分类ID
        $category_id = $this->request->request("category_id",0,"intval");

        // 商品数量
        $limit = 20;

        $where = array();

        $where['store_id'] = $this->store_id;

        // 商品状态:up=上架,hidden=隐藏商品,down=下架
        if($this->request->request("status",false)){
            $where['status'] = $this->request->request("status");
        }

        $order = 'weigh desc';

        if($category_id > 0){

            $data['list'] = Db::name('shopro_goods')->where($where)->where('find_in_set('.$category_id.',category_ids)')->order($order)->limit($offset, $limit)->select();

            // 商品数量
            $data['total'] = Db::name('shopro_goods')->where($where)->where('find_in_set('.$category_id.',category_ids)')->count();


        }else{

            // 查询商品数据
            $data['list'] = Db::name('shopro_goods')->where($where)->order($order)->limit($offset, $limit)->select();

            // 商品数量
            $data['total'] = Db::name('shopro_goods')->where($where)->count();

        }

        $this->success('请求成功', $data);

    }


    /***
     * @name    上传商品
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/06/01 16:41 PM
     * @return  string<json>
     */
    public function add_goods()
    {

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            $sku = $this->request->post("sku/a");

            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->validate('\app\admin\validate\shopro\Goods.add')->allowField(true)->save($params);
//                    echo $this->model->getlastsql();exit;
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    $this->editSku($this->model, $sku);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('上传成功');
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $this->error(__('Parameter %s can not be empty', ''));
        }

    }

    /***
     * @name    商品详情
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/06/09 14:58 PM
     * @return  string<json>
     */
    public function goods_info()
    {
        $goods_id = $this->request->get("goods_id");
        $row = $this->model->get($goods_id);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->updatetime = time();

        $skuList = \app\admin\model\shopro\GoodsSku::all(['pid' => 0, 'goods_id' => $goods_id]);

        if ($skuList) {
            foreach ($skuList as &$s) {
                $s->children = \app\admin\model\shopro\GoodsSku::all(['pid' => $s->id, 'goods_id' => $goods_id]);
            }
        }

        $skuPrice = \app\admin\model\shopro\GoodsSkuPrice::all(['goods_id' => $goods_id]);

        $this->success('商品信息获取成功', ['row'=>$row,'skuList'=>$skuList,'skuPrice'=>$skuPrice]);
    }

    /***
     * @name    编辑商品
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/06/02 10:29 PM
     * @return  string<json>
     */
    public function edit_goods()
    {
        $goods_id = $this->request->request("goods_id");
        $row = $this->model->get($goods_id);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->updatetime = time();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $sku = $this->request->post("sku/a");

            if ($params) {

                $result = false;
                Db::startTrans();
                try {
                    $result = $row->validate('\app\admin\validate\shopro\Goods.edit')->allowField(true)->save($params);
                    if (!$result) {
                        $this->error($row->getError());
                    } else {
                        $this->editSku($row, $sku);
                        Db::commit();
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));

        }else{

            $this->error(__('Parameter %s can not be empty', ''));

        }
    }


    /***
     * @name    上架/下架
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/06/02 15:37 PM
     * @return  string<json>
     */
    public function setStatus()
    {

        $goods_id = $this->request->post("goods_id",0,'intval');

        $status = $this->request->post("status");

        // 商品信息
        $result = Db::name('shopro_goods')->where(array('id'=>$goods_id))->update(array('status'=>$status));

        if($result){
            $this->success('设置成功');
        }else{
            $this->error('设置失败');
        }

    }




    /***
     * @name    编辑商品规格
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/06/01 17:13 PM
     * @return  string<json>
     */
    protected function editSku($goods, $sku)
    {

        // 提交上来的 商品 主规格
        $skuList = json_decode(htmlspecialchars_decode($sku['listData']), true);

        // 提交上来的 商品 规格具体信息
        $skuPrice = json_decode(htmlspecialchars_decode($sku['priceData']), true);

        // 是否重置规格（如果有改动，就先清空，然后重新添加规格）
        $is_set = isset($sku['is_set'])?intval($sku['is_set']):0;

        // 校验参数
        if (count($skuList) < 1) {
            $this->error('请填写规格列表');
        }
        if (count($skuPrice) < 1) {
            $this->error('请填写规格价格');
        }
        foreach ($skuPrice as &$price) {
            if (empty($price['price']) || $price['price'] == 0) {
                $this->error('请填写规格价格');
            }
            if ($price['stock'] === '') {
                $this->error('请填写规格库存');
            }
            if (empty($price['weight'])) {
                $price['weight'] = 0;
            }
        }

        // 查询是否存在商品主规格
        $goodsSku = \app\admin\model\shopro\GoodsSku::get(['goods_id' => $goods->id]);

        // 重置规格
        if($is_set == 1){

            // 先删除所有商品规格信息，然后生成
            @Db::name('shopro_goods_sku')->where(array('goods_id'=>$goods->id))->delete();
            @Db::name('shopro_goods_sku_price')->where(array('goods_id'=>$goods->id))->delete();

            // 新增商品规格信息
            return $this->insertGoodsSku($skuList, $skuPrice, $goods->id);

        }else{

            if (!$goodsSku) {

                // 新增商品规格信息
                return $this->insertGoodsSku($skuList, $skuPrice, $goods->id);

            } else {

                // 编辑原有信息
                $goodsSkuPrice = new \app\admin\model\shopro\GoodsSkuPrice;
                $goodsSkuPrice->saveAll($skuPrice);

            }

        }


    }


    /****
     * @name    新增商品规格
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/05/23 17:09 PM
     * @return  boolean
     */
    private function insertGoodsSku($skuList, $skuPrice, $goods_id)
    {

        // 初始化 sku 数组信息
        $allChildrenSku = [];

        //创建新产品，添加规格列表和规格价格
        foreach ($skuList as $s1 => &$k1) {

            //添加主规格
            $skuId[$s1] = \app\admin\model\shopro\GoodsSku::insertGetId([
                'name' => $k1['name'],
                'pid' => 0,
                'goods_id' => $goods_id
            ]);

            $k1['id'] = $skuId[$s1];

            // 添加子规格
            foreach ($k1['children'] as $s2 => &$k2) {
                $skuChildrenId[$s1][$s2] = \app\admin\model\shopro\GoodsSku::insertGetId([
                    'name' => $k2['name'],
                    'pid' => $k1['id'],
                    'goods_id' => $goods_id
                ]);
                $allChildrenSku[$k2['id']] = $skuChildrenId[$s1][$s2];
                $k2['id'] = $skuChildrenId[$s1][$s2];
                $k2['pid'] = $k1['id'];
            }
        }

        foreach ($skuPrice as $s3 => &$k3) {
            unset($k3['id']);
            $k3['goods_sku_ids'] = $this->checkRealIds($k3['goods_sku_ids'], $allChildrenSku);
            $k3['goods_id'] = $goods_id;
            $k3['goods_sku_text'] = implode(',', $k3['goods_sku_text']);
            $k3['weight'] = intval($k3['weight']);
        }

        // 添加商品规格 具体信息
        return \app\admin\model\shopro\GoodsSkuPrice::insertAll($skuPrice);

    }


    /****
     * @name    组装商品规格参数
     * @author  晓月老板<1434926265@qq.com>
     * @date    2020/05/23 17:09 PM
     * @return  boolean
     */
    private function checkRealIds($newGoodsSkuIds, $allChildrenSku)
    {
        $idsArray = explode(',', $newGoodsSkuIds);
        $newIdsArray = [];
        foreach ($idsArray as $id) {
            $newIdsArray[] = $allChildrenSku[$id];
        }
        return implode(',', $newIdsArray);

    }

}
